from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker

from commons.entity.po.user import User
from commons.mappers.base_mapper import BaseMapper

# 创建数据库引擎
db_url = "mysql+pymysql://root:123456@localhost/ctdb"
engine = create_engine(db_url, echo=True)

# 创建会话类
Session = sessionmaker(bind=engine)


class UserMapper(BaseMapper):
    def __init__(self):
        super().__init__(Session)

    def select_by_user_id(self, user_id):
        """
        根据 user_id 从数据库获取 User 对象
        :param user_id: str
        :return: User 对象或 None
        """
        try:
            with self.session_factory() as session:
                user = session.query(User).filter_by(user_id=user_id).first()
                if user:
                    return user
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None

    def delete_by_user_id(self, user_id):
        """
        根据 user_id 删除用户
        :param user_id: str
        :return: True（删除成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                user = session.query(User).filter_by(user_id=user_id).first()
                if user:
                    session.delete(user)
                    session.commit()  # 提交事务
                    return True
                return False  # 用户不存在
        except SQLAlchemyError as e:
            print(f"Database error during delete operation: {str(e)}")
            return False

    def update_by_user_id(self, user_update, user_id):
        """
        根据 user_id 更新用户信息
        :param user_id: str
        :param user_update: User 类实例或字典，包含需要更新的用户属性
        :return: True（更新成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                user = session.query(User).filter_by(user_id=user_id).first()
                if user:
                    # 如果 user_update 是类实例，转换为字典
                    if user_update and hasattr(user_update, 'to_dict'):
                        user_update = user_update.to_dict()

                    # 使用新数据更新用户属性
                    for key, value in user_update.items():
                        if value is not None and hasattr(user, key):
                            setattr(user, key, value)

                    session.commit()  # 提交事务
                    return True
                return False  # 用户不存在
        except SQLAlchemyError as e:
            print(f"Database error during update operation: {str(e)}")
            return False
